<template>
  <div ref="dataPermissionDrawer">
    <a-drawer title="数据权限" :width="860" :visible="visible" @close="onClose" :getContainer="() => $refs.dataPermissionDrawer">
      <secondary-title>基础信息</secondary-title>
      <a-form-model
        :model="roleForm"
        ref="roleForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row class="form-row">
          <a-col :span="8">
            <a-form-model-item label="身份名称" prop="name">
              {{ roleForm.name }}
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注信息">
              {{ roleForm.remark }}
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <secondary-title>权限设置</secondary-title>
      <transition name="fade">
        <div class="qiankun-alertTitle" v-show="isAlertTitle">
          <div>
            <a-icon type="exclamation-circle" theme="filled" />
            请谨慎分配标记【*】的功能权限，随意分配这些权限可能会给您带来潜在风险。
          </div>
          <a-icon @click="isAlertTitle = false" type="close" />
        </div>
      </transition>
      <!-- 权限设置 -->
      <a-card class="qiankun-permission-tree">
        <data-permission-router-tree
          v-loading="isLoading"
          ref="tree"
          :treeData="treeData"
          :roleInfo="roleForm"
          :pageType="type"
          :syncData="syncDataFn"
        ></data-permission-router-tree>
      </a-card>
      <a-row class="mt30" type="flex" justify="end">
        <a-button class="mr20" @click="onClose">取消</a-button>
        <a-button v-show="!isDetail" type="primary" @click="onSave"
          >保存</a-button>
      </a-row>
    </a-drawer>
  </div>
</template>
<script>
import dataPermissionRouterTree from "./dataPermissionRouterTree.vue";
import { PLACEHOLDER_INPUT, TITLE_OBJECT } from "@/config/const";
import { SecondaryTitle } from "@/components/common";
import { changePlaceholder } from "@/utils/util";
import { mapGetters } from "vuex";
import {
  getNewDataPermissionTree,
  saveNewDataPermission
} from "@/services/roleManage.js";
import { popDimensionList } from '../config';

const originForm = {
  id: undefined,
  name: "",
  remark: "",
  departmentId: "",
  enterpriseId: ""
};

export default {
  name: "permissionDrawer",
  props: {
    showCheckbox: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      changePlaceholder,
      PLACEHOLDER_INPUT,
      TITLE_OBJECT,
      visible: false,
      roleForm: { ...originForm },
      treeData: [],
      treeNodeKey: "id",
      isLoading: false,
      treeDetailList: [],
      isAlertTitle: true,
      type: "add",
      permissionList: [] // 提交时的参数
    };
  },
  components: {
    dataPermissionRouterTree,
    SecondaryTitle
  },
  mounted() {
  },
  computed: {
    ...mapGetters("account", ["enterpriseId"]),
    isDetail() {
      return this.type === "view";
    },
    isEdit() {
      return this.type === "edit";
    },
    id() {
      return this.$route.query.id;
    }
  },
  methods: {
    showDrawer(data, type) {
      this.type = type;
      this.visible = true;
      this.roleForm = { ...data };
      this.getTree()
    },
    onClose() {
      this.visible = false;
      this.isAlertTitle = true;
    },
    // 全部权限tree
    async getTree() {
      this.isLoading = true;
      try {
        const { id, departmentId } = this.roleForm
        let { data: { data, code } } = await getNewDataPermissionTree({roleId: id, departmentId});
        if (code !== 200) {
          this.treeData = []
          return
        }
        this.treeData = [data];
      } catch(e) {
        console.log(e)
      } finally {
        this.isLoading = false;
      }
    },
    // 同步树的数据
    syncDataFn(list) {
      this.permissionList = list;
    },
    // 处理提交时的参数
    saveParamsHandler() {
      // 1. 定义最终参数
      const result = []
      // 2. 定义递归程序
      const recursionFn = (item) => {
        // 2.1 获取当前值
        const { route, dimension, permissionList, children } = item
        // 2.2 基于permissionList查找是否匹配
        const matchIndex = this.permissionList.findIndex((item) => item.route === route)
        const isMatch = matchIndex !== -1
        let value, _dimension;
        // 2.3 基于是否匹配进行更新参数
        if (isMatch) {
          const current = this.permissionList[matchIndex]
          value = current.value
          _dimension = current.dimension
        } else {
          value = permissionList
          _dimension = dimension
        }
        // 2.4 基于弹窗列表对参数进行过滤
        const popDimensionFlag = popDimensionList.includes(_dimension)
        popDimensionFlag && !value.length && (_dimension = '')
        result.push({ route, dimension: _dimension, value })
        // 2.5 继续递归
        if (children && children?.length) {
          children.forEach((item)=>{
            recursionFn(item)
          })
        }
      }
      // 3. 启动递归程序
      this.treeData.forEach((item)=>{
        recursionFn(item)
      })
      // 4. 返回结果
      return result
    },
    // 保存
    async onSave() {
      // 保存接口
      const { id, departmentId } = this.roleForm
      const params = {
        permissionList: this.saveParamsHandler(),
        departmentId,
        roleId: id
      }
      try {
        const { data: { message, code } } = await saveNewDataPermission(params);
        if (code !== 200) {
          this.$message.error(message || "保存失败");
          return
        }
        this.$message.success("保存成功");
        this.$emit("success");
      } catch (error) {
        this.$message.error(error);
      } finally {
        this.visible = false;
      }
    },
    // drawer的挂载节点
    getContainer() {
      return document.querySelector('#qiankun-role-manage');
    }
  }
};
</script>
<style lang="less" scoped>、
.form-row {
  margin: 8px 0;
}

.title-item {
  font-size: 14px;
  font-weight: 600;
}

/deep/ .ant-form label {
  font-size: 14px!important;
}

/deep/ .secondary-title {
  font-size: 14px!important;
  font-weight: 400!important;
  color: rgba(0,0,0,.65)!important;
  line-height: 40px;
  position: relative;
  top: -10px;
}

// 身份权限设置警告
.qiankun-alertTitle {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin: auto;
  color: red;
  border: 1px solid red;
  padding: 4px 10px;
  font-size: 14px;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.qiankun-permission-tree {
  margin-bottom: 10px!important;
  max-height: 49vh;
  overflow-y: auto;
  ::v-deep .ant-drawer-title {
    font-weight: 600;
    font-size: 18px;
  }
}
</style>
